/**
 *   This file is part of WiFiStorer.

    WiFiStorer is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    WiFiStorer is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with WiFiStorer.  If not, see <http://www.gnu.org/licenses/>.
    
    @author Ontic Soluciones
    @license GNU GPLv3
    @copyright 2010 Ontic Soluciones
    @link http://www.ontic.es
    @contact android@ontic.es
 */


package com.Storer;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Environment;


/**
 * Lee de la tabla que se le pasa como parámetro y crea un documento .Kml de acuerdo con el estandar
 * de Google para mostrar las redes en GoogleEarth.
 *  @license GNU GPLv3
    @copyright 2010 Ontic Soluciones
    @link http://www.ontic.es
    @contact android@ontic.es
 *
 */
public class Kml
{
	private BufferedWriter  bw;
	private SQLiteDatabase DB = null;
	private DataBaseHelper db;
	private String tabla;
	private String clasif;
	private int power;
	
	/**
	 * Constructor de la clase, crea una nueva instancia de Kml
	 * @param context el contexto de la actividad que lo llama, para abrir un DBHelper
	 * @param tabla la tabla a exportar
	 */
	public Kml(Context context, String tabla)
	{
		db = new DataBaseHelper(context);
        DB =  db.getReadableDatabase();
        this.tabla = tabla;  
	}

	/**
	 * Crea el fichero .kml en la tarjeta de memoria, y un buffer va escribiendo los datos de la tabla 
	 * con el formato adecuado.
	 */
	public void copiar() 
	{
       
		// TODO Auto-generated method stub
		 //Abrimos un File a la ruta donde se guardará
        File path = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/kmls");
		//File path = new File(Environment.getRootDirectory().getAbsolutePath()+"/kmls"); 
        if(!path.exists())
            path.mkdirs();
        
        //Creamos el fichero en la ruta
        //File f = new File(path, "t"+formato.format(new java.util.Date()) + ".kml");
        File f = new File(path, tabla+".kml");
        
        //Creamos el Stream para escribir
        try 
        {
        	 bw = new BufferedWriter(new FileWriter(f.getAbsolutePath()));
		} catch (FileNotFoundException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) 
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	        String select = "select _id, lat, lng, alt, ssid, bssid, pow, prot from "+tabla;
	        Cursor c = DB.rawQuery(select, null);

	        select = "select distinct bssid from "+tabla+" order by ssid";
	        Cursor d = DB.rawQuery(select, null);   
			
			try 
			{
				bw.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<kml xmlns=\"http://earth.google.com/kml/2.x\">\n<Document>\n" +
						"<Style id=\"Azul\"> <IconStyle> <Icon> <href>http://maps.google.com/mapfiles/kml/pushpin/blue-pushpin.png</href>" +
						"</Icon> </IconStyle> </Style> <Style id=\"Roja\"><IconStyle>" +
						"<Icon>	<href>http://maps.google.com/mapfiles/kml/pushpin/red-pushpin.png</href></Icon>" +
						"</IconStyle></Style><Style id=\"Amarilla\"><IconStyle><Icon><href>http://maps.google.com/mapfiles/kml/pushpin/ylw-pushpin.png</href>" +
						" </Icon></IconStyle></Style><Style id=\"Verde\"><IconStyle><Icon><href>http://maps.google.com/mapfiles/kml/pushpin/grn-pushpin.png</href>" +
						" </Icon></IconStyle></Style> " +
						"<Style id=\"Morada\"><IconStyle><Icon><href>http://maps.google.com/mapfiles/kml/pushpin/purple-pushpin.png</href>" +
						" </Icon></IconStyle></Style>");
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			if(c.moveToFirst() && d.moveToFirst())
	        {        	
	        	for(int j=0; j< d.getCount()-1; j++)
	        	{
	        		select = "select distinct ssid from "+tabla+" where bssid='"+d.getString(0)+"'";
	    			Cursor kml = DB.rawQuery(select, null);
					kml.moveToFirst();
			
	        		try {	
	        			String name=kml.getString(0);
	        			bw.write("<Folder>\n<name>"+name+" ("+d.getString(0)+")</name>\n");
						//C -> Toda la tabla ; D -> Solo 1 red
						for(int i = 0; i< c.getCount()-1; i++)
						{
							if(d.getString(0).equals(c.getString(5)))
							{
								 if (name.contains("&"))
					    			  name.replace("&", "Y");
								 power = c.getInt(6);
								 if(power <=65 )
									 clasif="Roja";
								 if(power >65 && power <=75)
									 clasif="Amarilla";
								 if(power >75 && power <=80)
									 clasif="Verde";
								 if(power <80 && power < 85)
									 clasif="Morada";
								 if(power>85)
									 clasif="Azul";
								 
								bw.write("<Placemark id=\""+kml.getString(0)+"\" >\n<name>"+name +
										"</name>\n" +
										"<styleUrl>#"+clasif+"</styleUrl> " +
										"<Point> <coordinates>"+((double)c.getInt(2))/1000000+","+((double)c.getInt(1))/1000000+",0" +
										" </coordinates></Point>\n</Placemark>\n");
							}
							c.moveToNext();
						}
						d.moveToNext();
						c.moveToFirst();
						kml.moveToNext();
						
						bw.write("</Folder>\n");
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
	        	}
	        	try 
	        	{
					bw.write("</Document>\n</kml>\n");
					bw.close();
					DB.close();

				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
	        }
	}

}